package com.taptech.doufu.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.BaseBean;
import com.taptech.doufu.bean.cartoon.CartoonBean;
import com.taptech.doufu.bean.MineAbstractBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.MySwipeRefreshLayout;
import com.taptech.doufu.ui.view.drawcircle.RecyclerViewAdapterAsListView;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.URLParseUtils;
import com.taptech.doufu.net.httputils.HttpRequestObject;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by longsiyang on 15/12/14.
 */
public class DoufuContentFragment<T extends BaseBean> extends Fragment implements HttpResponseListener, View.OnClickListener {

    protected Context mContext;

    // UI控件
    protected View rootView;
    protected MySwipeRefreshLayout swipeLayout;
    protected MyRecyclerView listView;
    protected RecyclerViewAdapterAsListView adapter;
    protected ProgressBar waitBar;


    // 数据
    public List<MineAbstractBean> mDataList;
    protected String last = "";
    protected boolean hasMoreContent = true;

    private boolean isNeedReParse = false;


    public DoufuContentFragment() {

    }

    public DoufuContentFragment(boolean isNeedReParse) {
        this.isNeedReParse = isNeedReParse;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.doufu_content_listview_fragment, container, false);
        mContext = getActivity();
        initData();
        initView();
        //拉取数据
        listViewRefresh();
        initWaitWindow();
        //initTestData();
        return rootView;
    }


    private String tempSting;

    @Override
    public void handleResponse(int handleType, final HttpResponseObject response) {
        tempSting = URLParseUtils.parseB(url);
        if (response.getStatus() == Constant.STATUS_SUCCESS) {
            if ((last == null) || (last.equals(""))) {
                //写缓存
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                    }
                }).start();
            }
            HttpUtil.setOnHandleHttpResponListener(mContext, handleType, response, listener);
        } else {
            if ((last == null) || (last.equals(""))) {
                try {
                    //读取缓存
                    UIUtil.toastMessage(getActivity(), DiaobaoUtil.getErrorTips(response));
                    JSONObject data = CacheUtil.readJsonDataFromCache(new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + tempSting));
                    if (waitBar != null) {
                        waitBar.setVisibility(View.GONE);
                    }
                    displayHttpData(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                UIUtil.toastMessage(getActivity(), DiaobaoUtil.getErrorTips(response));
            }
        }
    }

    HttpUtil.HandleHttpResponListener listener = new HttpUtil.HandleHttpResponListener() {
        @Override
        public void handleRespon(int handleType, JSONObject data) {
            final int fragmentHandleType = DoufuContentFragment.this.handleType;
            if (waitBar != null) {
                waitBar.setVisibility(View.GONE);
            }
            if (fragmentHandleType == handleType) {
                displayHttpData(data);
            }
        }
    };

    @Override
    public void onClick(View view) {

    }


    protected void initData() {
        mDataList = new ArrayList<MineAbstractBean>();
    }

    protected void initTestData() {
        for (int i = 0; i < 20; i++) {
            CartoonBean bean = new CartoonBean();
            bean.setObject_type(String.valueOf(Constant.OBJECT_TYPE_CARTOON));
            mDataList.add(bean);
        }
        adapter.notifyDataSetChanged();
    }

    protected void initView() {
        waitBar = (ProgressBar) rootView.findViewById(R.id.xlistview_footer_progressbar);
        swipeLayout = (MySwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
        swipeLayout.setOnRefreshListener(new MySwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                listViewRefresh();
                //关闭刷新动画
                swipeLayout.setRefreshing(false);
                //关闭下拉使能已免
                swipeLayout.setEnabled(false);
                //显示顶部刷新等待窗
                waitBar.setVisibility(View.VISIBLE);
            }
        });
        adapter = new RecyclerViewAdapterAsListView(mContext, mDataList,coverType);
        listView = (MyRecyclerView) rootView.findViewById(R.id.recycler_view_id);
        RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
        listView.setLayoutManager(layoutManager);
        listView.setAdapter(adapter);
        listView.setOnScrollToTopListener(new MyRecyclerView.OnScrollToTopListener() {
            @Override
            public void refresh() {
                swipeLayout.setEnabled(true);
            }

            @Override
            public void notAtTopInScrollView(int offestY, int directionY) {
                swipeLayout.setEnabled(false);

            }
        });
        listView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener() {
            @Override
            public void loadMore() {
                //Toast.makeText(DrawCircleActivity.this, "已到底部", Toast.LENGTH_SHORT).show();
                listViewLoadMore();
            }
        });
    }


    /**
     * 拉取数据请求
     */
    protected synchronized void listViewRefresh() {
        last = "";
        if (adapter != null) {
            adapter.pullComplete(false);
        }
        sendGetRequest();
    }

    /**
     * 加载更多
     */
    protected synchronized void listViewLoadMore() {
        if (hasMoreContent) {
            hasMoreContent = false;
            sendGetRequest();
        }
    }


    protected void displayHttpData(JSONObject data) {
        try {
            if (adapter == null) {
                return;
            }
            // 判断是否还有更多内容
            if (last.equals(data.getString("last"))) {
                hasMoreContent = false;
                adapter.pullComplete(true);

            } else {
                hasMoreContent = true;
                adapter.pullComplete(false);

            }
            // 如果是第一波数据
            if (last.equals("") && mDataList != null) {
                mDataList.clear();
                adapter.notifyDataSetChanged();
            }
            if (isNeedReParse) {
                List dataList = com.alibaba.fastjson.JSONArray.parseArray(data.getJSONArray(dataName).toString(), classType);
                mDataList.addAll(dataList);
            } else {
                JSONArray jsonArray = data.getJSONArray(dataName);
                List dataList = DiaobaoUtil.json2list(classType, jsonArray);
                mDataList.addAll(dataList);
            }

            adapter.notifyDataSetChanged();
            last = data.getString("last");
        } catch (JSONException e) {
            UIUtil.toastMessage(getActivity(), "网络异常，请检查网络后再试");
            e.printStackTrace();
        }

    }


    /**
     * 进入界面时的等待窗
     */
    protected void initWaitWindow() {

    }


    public interface RequesHelper {
        void httpRequest(String last);
    }

    protected String dataName;
    protected Class classType;
    protected int handleType;
    protected String url;
    protected int coverType;




    public void setArgument(String dataName, Class classType, int handleType, String url,int coverType) {
        this.dataName = dataName;
        this.classType = classType;
        this.handleType = handleType;
        this.coverType = coverType;
        this.url = url;
    }

    public void setArgument(String dataName, Class classType, int handleType, String url) {
        this.dataName = dataName;
        this.classType = classType;
        this.handleType = handleType;
        this.url = url;
    }

    protected void sendGetRequest() {
        HttpRequestObject request = new HttpRequestObject();
        request.setHandleType(handleType);
        try {
            request.setUrl(url + "&last=" + URLEncoder.encode(last, "utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.setListener(this);
        HttpUtil.sendGetRequest(request);
    }
   public void changeModel(){
       if(adapter != null){
           adapter.notifyDataSetChanged();
       }
       if(WeMediaApplication.getInstance().isDayNightMode_Night){
           swipeLayout.setBackgroundColor(getResources().getColor(R.color.bg_dark));
           waitBar.setAlpha(Constant.imagViewAlpha);
       }else {
           swipeLayout.setBackgroundColor(getResources().getColor(R.color.all_activity_background));
           waitBar.setAlpha(1.0f);
       }
   }
}
